package com.kaesun.ufit.hardware;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import android.os.Message;

import com.kaesun.ufit.serialport.SerialPort;
import com.kaesun.ufit.weight.MainApplication;
import com.kaesun.ufit.weight.WeakRefHandler;

public class HallSensor {

	private static final String DEVICE_HALL_SENSOR = "/dev/ttyO4";
	private static final int BAUDRATE_HALL_SENSOR = 9600;

	private SerialPort mSerialPort = null;
	private ReadThread mReadThread = null;
	private WeakRefHandler mHandler = null;

	public void start() {
		if (null == mSerialPort) {
			try {
				mSerialPort = new SerialPort(new File(DEVICE_HALL_SENSOR), BAUDRATE_HALL_SENSOR, 0);

				mReadThread = new ReadThread(mSerialPort);
				mReadThread.start();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void stop() {
		if (null != mReadThread) {
			mReadThread.interrupt();
			mReadThread = null;
		}
		if (null == mSerialPort) {
			mSerialPort.close();
			mSerialPort = null;
		}
	}

	public void setHandler(WeakRefHandler handler) {
		mHandler = handler;
	}


	public void zero() {
		try {
			mSerialPort.getOutputStream().write('Z');
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	private class ReadThread extends Thread {
		private InputStream mInputStream = null;
		private int mLastPosition = -1;
		private int mNoiseCount = 0;

		public ReadThread(SerialPort sp) {
			mInputStream = sp.getInputStream();
		}

		@Override
		public void run() {
			super.run();

			if (null == mInputStream) {
				return;
			}

			byte[] buf = new byte[16];
			int size = 0;
			while (!isInterrupted()) {
				try {
					size = mInputStream.read(buf);
					if (size > 0) {
						// sprintf(">%d,%d\r\n", pos, val);
						if ((6 <= size) && ('>' == buf[0])) {
							for (int i=1; i<size; i++) {
								if (',' == buf[i]) {
									int position = Integer.parseInt(new String(buf, 1, i-1));
									//int level = Integer.parseInt(new String(buf, i+1, size-(i+1)-2));

									//int offset = Math.abs(mLastPosition - position);
									int offset = mLastPosition - position;
									if (20 < offset) {
										// noise...
										if (2 > ++mNoiseCount) {
											position = mLastPosition;
										}
										//Log.e("aaa", "position=" + position + ", offset=" + offset + ", count=" + mNoiseCount);
									} else {
										mNoiseCount = 0;
									}

									if (null != mHandler) {
										mHandler.sendMessage(Message.obtain(mHandler, MainApplication.HANDLER_RX_HALLSENSOR, position, Math.abs(offset)));
									}
									mLastPosition = position;

									break;
								}
							}
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
					return;
				}
			}
		}
	}
}
